﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Item : MonoBehaviour
{
	Image image => GetComponent<Image>();
	public bool show { get; set; }      // 是否隐藏
	public int num { get; set; }        // 周围炸弹数
	public bool flag { get; set; }      // 标记为旗子
	public int id { get; set; }         // item id可记录位置
	Grid grid => transform.parent.GetComponent<Grid>();
	GameRoot gameRoot => GameRoot.Instance;

	bool cover => gamePanel.pause;
	GamePanel gamePanel;
	// Start is called before the first frame update
	void Start() {
		gamePanel = gameRoot.uiMng.GetPanel(UIPanelType.GamePanel) as GamePanel;
	}



	/// <summary>
	/// 展示数字
	/// </summary>
	/// <param name="num"></param>
	public void Show_Num(int num) {
		image.sprite = Resources.Load<Sprite>(num.ToString());
		SelectRequest selectRequest = transform.parent.GetComponent<SelectRequest>();
		if (selectRequest != null && gameRoot.Online)
			selectRequest.RequestSelect(id / grid.column, id % grid.column, num.ToString());
	}

	/// <summary>
	/// 展示, 旗子, 未选中, 炸弹等
	/// </summary>
	/// <param name="path"></param>
	public void Show_UI(string path) {
		image.sprite = Resources.Load<Sprite>(path);
		SelectRequest selectRequest = transform.parent.GetComponent<SelectRequest>();
		if (selectRequest != null && gameRoot.Online)
			selectRequest.RequestSelect(id / grid.column, id % grid.column, path);
	}




	#region 鼠标点击事件
	public void OnClickMouse0() {
		if (show || flag) return;   // 左键点击了已显示数字或flag

		if (num == -1) {            // 点了炸弹
			grid.OnClickMine0(id);
		} else {
			grid.OnClickNum0(id);
		}
	}

	public void OnClickMouse1() {

		if (show) {        // 已经打开的
			grid.OnClickShow1(id);
		} else {            // 未打开的
			grid.OnClickHide1(id);
		}
	}

	#endregion







	bool click;
	void Update() {
		bool isUI = RectTransformUtility.RectangleContainsScreenPoint(GetComponent<RectTransform>(), Input.mousePosition);
		if (isUI) {

			if (!cover && Input.GetKeyDown(KeyCode.Mouse0)) {
				if (!show && !flag) {
					click = true;
					image.color = new Color(0.8f, 0.8f, 0.8f, 0.5f);
				}
			}

			if (!cover && Input.GetKeyUp(KeyCode.Mouse0))     // 左键点击
			{
				if (click) {
					OnClickMouse0();
				}
				image.color = new Color(1, 1, 1, 1);
				click = false;
			}

			if (!cover && Input.GetKeyUp(KeyCode.Mouse1))     // 右键点击
			{
				// Show_UI(true);
				OnClickMouse1();
			}
		} else {
			click = false;
			image.color = new Color(1, 1, 1, 1);
		}

	}


	public static Item GenerateInitItem(int num, Transform parent) {
		GameObject itemPrefab = Resources.Load<GameObject>("Item");
		Item item = Instantiate(itemPrefab, parent).GetComponent<Item>();

		item.GetComponent<Image>().sprite = Resources.Load<Sprite>("hide");
		item.show = false;
		item.num = num;
		item.flag = false;
		return item;
	}
}
